package tech.xs.common.framework.util;

import cn.hutool.core.bean.BeanUtil;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import tech.xs.common.framework.domain.exception.BaseException;
import tech.xs.common.framework.domain.model.ApiResult;
import tech.xs.common.framework.holder.SpringContextHolder;
import tech.xs.common.sys.domain.bo.SysConfigBo;
import tech.xs.common.sys.domain.constant.SysCacheKeyConstant;

import java.util.HashMap;
import java.util.Map;

public class SysConfigUtil {

    public static SysConfigBo getConfig(String code) {
        RedissonClient redissonClient = SpringContextHolder.getBean(RedissonClient.class);
        RBucket<SysConfigBo> bucket = redissonClient.getBucket(SysCacheKeyConstant.SYS_CONFIG_CACHE + code);
        if (bucket.isExists()) {
            return bucket.get();
        }
        Environment environment = SpringContextHolder.getBean(Environment.class);
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("code", code);
        ResponseEntity<ApiResult> response = DynamicRequestUtil.get(environment.getProperty("framework.service.sys.name"), "/config/getConfig", requestParam, ApiResult.class);
        ApiResult<?> apiResult = response.getBody();
        if (!apiResult.isSuccess()) {
            throw new BaseException("sys服务调用失败 apiResult:" + apiResult);
        }
        Object data = apiResult.getData();
        SysConfigBo res = new SysConfigBo();
        BeanUtil.copyProperties(data, res);
        if (data != null) {
            bucket.set(res);
            return res;
        }
        return null;
    }

    public static String getStringConfigData(String code) {
        SysConfigBo config = getConfig(code);
        if (config == null) {
            return null;
        }
        return config.getData();
    }

}
